//Author: Soeren Pirk
//Date: 11.04.2013
//Edited: Thomas Lindemeier
//Date: 31.03.2014
//
#include "Global.h"
#include "Renderer.h"
#include "Scene.h"

double old_time = 0;

Renderer::Renderer(Scene *scene)
: m_width(0),
  m_height(0),
  m_zoom(-80.0f),
  m_scene(scene),
  m_rotate(-45.0f,0.0f)
{    
}

Renderer::~Renderer()
{
}

void Renderer::init()
{
    glEnable(GL_MULTISAMPLE);    
    glEnable(GL_DEPTH_TEST);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}

void Renderer::render()
{
    glClearColor(1.0f, 1.0f, 1.0f, 1); 
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  

    Transform trans;

	trans.projection = mat4::perspective(45.0f, (GLfloat)m_width / (GLfloat)m_height, 1.0, 1000.0f);

	trans.view = mat4::translate(vec3(0, 0, m_zoom));
	trans.view *= mat4::rotate(m_rotate.x, 1, 0, 0);
	trans.view *= mat4::rotate(m_rotate.y, 0, 1, 0); 

	double time = glfwGetTime();
    m_scene->update(time-old_time);
    old_time = time;
    m_scene->render(trans);
}

void Renderer::resize(GLint width, GLint height)
{
    m_width = width;
    m_height = height;

    printf("WindowSize: %d, %d\n", width, height);

    glViewport(0, 0, m_width, m_height);
}

void Renderer::onMouseWheel(GLboolean positive)
{    
    GLfloat delta = m_zoom * 0.1f;

    if(positive)
    {
        m_zoom += delta;
    }
    else
    {
        m_zoom -= delta;
    }
}

void Renderer::onMouseMove(vec2 delta)
{
    m_rotate.y -= (0.1f * delta.x);
    m_rotate.x -= (0.1f * delta.y);	
}
